using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using System.ComponentModel.DataAnnotations;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 用户认证管理接口。
    /// 提供用户注册、登录、密码重置、短信验证码、用户信息管理等相关功能的 API。
    /// </summary>
    [ApiController]
    [Route("api/auth")]
    public class AuthenticationController : ControllerBase
    {
        /// <summary>
        /// 认证应用服务接口
        /// </summary>
        private readonly IAuthenticationAppService _service;
        
        /// <summary>
        /// 构造函数，注入认证服务
        /// </summary>
        /// <param name="service">认证应用服务接口</param>
        public AuthenticationController(IAuthenticationAppService service)
        {
            _service = service;
        }

        /// <summary>
        /// 用户注册
        /// 创建新用户账户，需要提供用户名、邮箱、密码等基本信息
        /// </summary>
        /// <param name="dto">用户注册请求数据传输对象</param>
        /// <returns>注册结果</returns>
        /// <response code="200">注册成功</response>
        /// <response code="400">请求参数无效或用户已存在</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("register")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> Register([FromBody] RegisterRequestDto dto)
        {
            await _service.RegisterAsync(dto.Username, dto.Email, dto.Password, dto.Phone);
            return Ok(new { Message = "注册成功" });
        }

        /// <summary>
        /// 用户登录
        /// 使用用户名和密码进行身份验证，成功后返回访问令牌
        /// </summary>
        /// <param name="dto">用户登录请求数据传输对象</param>
        /// <returns>登录结果，包含访问令牌和刷新令牌</returns>
        /// <response code="200">登录成功，返回令牌信息</response>
        /// <response code="401">用户名或密码错误</response>
        /// <response code="400">请求参数无效</response>
        /// <response code="500">服务器内部错误</response>
        [HttpPost("login")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(401)]
        [ProducesResponseType(400)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> Login([FromBody] LoginRequestDto dto)
            => Ok(await _service.LoginAsync(dto.Username, dto.Password));

        /// <summary>
        /// 刷新访问令牌
        /// </summary>
        /// <param name="dto">刷新令牌请求数据传输对象</param>
        /// <returns>新的访问令牌</returns>
        [HttpPost("refresh-token")]
        public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequestDto dto)
            => Ok(await _service.RefreshTokenAsync(dto.RefreshToken));

        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="dto">短信验证码请求数据传输对象</param>
        /// <returns>发送结果</returns>
        [HttpPost("send-sms-code")]
        public async Task<IActionResult> SendSmsCode([FromBody] SmsCodeRequestDto dto)
        {
            await _service.SendSmsCodeAsync(dto.Phone);
            return Ok();
        }

        /// <summary>
        /// 验证短信验证码
        /// </summary>
        /// <param name="dto">短信验证码验证请求数据传输对象</param>
        /// <returns>验证结果</returns>
        [HttpPost("verify-sms-code")]
        public async Task<IActionResult> VerifySmsCode([FromBody] VerifySmsCodeRequestDto dto)
            => Ok(await _service.VerifySmsCodeAsync(dto.Phone, dto.Code));

        /// <summary>
        /// 请求密码重置
        /// </summary>
        /// <param name="dto">密码重置请求数据传输对象</param>
        /// <returns>请求结果</returns>
        [HttpPost("password-reset/request")]
        public async Task<IActionResult> RequestPasswordReset([FromBody] PasswordResetRequestDto dto)
        {
            await _service.RequestPasswordResetAsync(dto.Email);
            return Ok();
        }

        /// <summary>
        /// 确认密码重置
        /// </summary>
        /// <param name="dto">密码重置确认数据传输对象</param>
        /// <returns>重置结果</returns>
        [HttpPost("password-reset/confirm")]
        public async Task<IActionResult> ConfirmPasswordReset([FromBody] PasswordResetConfirmDto dto)
            => Ok(await _service.ConfirmPasswordResetAsync(dto.Email, dto.Code, dto.NewPassword));

        /// <summary>
        /// 获取当前用户信息（需要身份验证）
        /// </summary>
        /// <returns>当前用户信息</returns>
        [Authorize]
        [HttpGet("me")]
        public async Task<IActionResult> Me()
            => Ok(await _service.GetCurrentUserAsync());

        /// <summary>
        /// 获取当前JWT令牌信息（需要身份验证）
        /// </summary>
        /// <returns>JWT令牌信息</returns>
        [Authorize]
        [HttpGet("token-info")]
        public IActionResult GetTokenInfo()
        {
            var claims = HttpContext.User.Claims.Select(c => new 
            { 
                Type = c.Type, 
                Value = c.Value 
            }).ToList();

            return Ok(new 
            { 
                IsAuthenticated = HttpContext.User.Identity?.IsAuthenticated ?? false,
                AuthenticationType = HttpContext.User.Identity?.AuthenticationType,
                Name = HttpContext.User.Identity?.Name,
                Claims = claims
            });
        }

        /// <summary>
        /// 用户登出（需要身份验证）
        /// </summary>
        /// <returns>登出结果</returns>
        [Authorize]
        [HttpPost("logout")]
        public async Task<IActionResult> Logout()
        {
            await _service.LogoutAsync();
            return Ok();
        }
    }
}
